package com.training.java.redbox.domain;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;


@Repository
public class MovieDAOJDBCImpl implements MovieDAO {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public List<Movie> getAllMovies() throws DAOException {
		
		return jdbcTemplate.query("Select * from Movie", new MovieRowMapper());

	}


		@Override
		public void deleteMovie(long id) throws DAOException {
			
			jdbcTemplate.update("delete from movie where id = ?", id);
		}

		@Override
		public Movie findByPrimaryKey(long movieId) throws DAOException {
			
			try{
			return jdbcTemplate.queryForObject("Select * from Movie where  id = ?", new MovieRowMapper(), movieId);
			}catch(EmptyResultDataAccessException erdae){
					return null;
			}
		}

		private static final class MovieRowMapper implements RowMapper<Movie>{

			@Override
			public Movie mapRow(ResultSet resultSet, int arg1) throws SQLException {
				
				long id = resultSet.getLong("ID");
				String type = resultSet.getString("TYPE");
				String title = resultSet.getString("TITLE");
				double rentalPrice = resultSet.getDouble("RENTAL_PRICE");
				String imageLocation = resultSet.getString("image_location");

				Movie movie = new Movie(id, type, title, rentalPrice, imageLocation);

				return movie;
			}
			
		}
	}
